package com.xpp.yanpicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.xpp.yanpicturebackend.config.CosClientConfig;
import com.xpp.yanpicturebackend.exception.BusinessException;
import com.xpp.yanpicturebackend.exception.ErrorCode;
import com.xpp.yanpicturebackend.exception.ThrowUtils;
import com.xpp.yanpicturebackend.model.dto.file.UploadPicturesResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
@Deprecated
public class FileManager {
    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     *
     * @param multipartFile    文件
     * @param uploadPathPrefix 上传路径前缀
     * @return
     */
    public UploadPicturesResult uploadPictures(MultipartFile multipartFile, String uploadPathPrefix) {
        // 校验图片
        validPicture(multipartFile);
        // 图片上传地址
        String uuid = RandomUtil.randomString(6);
        String originalFilename = multipartFile.getOriginalFilename();
        String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getPrefix(originalFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
        // 解析并返回结果
        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = File.createTempFile(uploadPath, null);
            // 存储到临时文件中
            multipartFile.transferTo(tempFile);
            // 上传到 COS
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, tempFile);
            // 获取图片信息对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 封装返回对象
            String format = imageInfo.getFormat();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();

            UploadPicturesResult uploadPicturesResult = new UploadPicturesResult();
            uploadPicturesResult.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            uploadPicturesResult.setName(FileUtil.mainName(originalFilename));
            uploadPicturesResult.setPicSize(FileUtil.size(tempFile));
            uploadPicturesResult.setPicWidth(picWidth);
            uploadPicturesResult.setPicHeight(picHeight);
            uploadPicturesResult.setPicScale(picScale);
            uploadPicturesResult.setPicFormat(format);

            // 返回封装好的对象
            return uploadPicturesResult;
        } catch (Exception e) {
            log.error("file upload error, filepath = " + uploadPath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            //删除临时文件
            deleteTempFile(tempFile);
        }
    }


    /**
     * 校验文件
     *
     * @param multipartFile 文件
     */
    private void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAM_ERROR, "文件不能为空");
        // 1. 校验文件大小
        long size = multipartFile.getSize();
        final long ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(size > 2 * ONE_M, ErrorCode.PARAM_ERROR, "文件大小不能超过 2M");
        // 2. 校验文件后缀
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        // 允许上传的文件集合
        final List<String> ALLOW_FORAMT_LIST = Arrays.asList("jpg", "jpeg", "png", "webp");
        ThrowUtils.throwIf(!ALLOW_FORAMT_LIST.contains(suffix), ErrorCode.PARAM_ERROR, "文件类型错误");
    }

    /**
     * 清理临时文件
     *
     * @param tempFile
     */
    public static void deleteTempFile(File tempFile) {
        if (tempFile == null) {
            return;
        }
        // 删除临时文件
        boolean delete = tempFile.delete();
        if (!delete) {
            log.error("file delete error,file = {}", tempFile);
        }
    }
}
